package controllers.admin

import controllers.{RequestAsJson, checkAdmin}
import models.users._

import javax.inject._
import play.api.Logging
import play.api.libs.json.{JsError, Json}
import play.api.mvc._
import security.access.PermissionAccess

import scala.concurrent.{ExecutionContext, Future}

/**
 * This controller creates an `Action` to handle HTTP requests to the
 * application's home page.
 */
@Singleton
class UsersController @Inject()(cc: ControllerComponents,
                                usersRepo: UsersRepository)(implicit exec: ExecutionContext, parser: BodyParsers.Default)
  extends AbstractController(cc) with RequestAsJson with Logging {
  //implicit val myCustomCharset = Codec.javaSupported("gb18030")

  /**
   * Create an Action to render an HTML page with a welcome message.
   * The configuration in the `routes` file means that this method
   * will be called when the application receives a `GET` request with
   * a path of `/`.
   */
  def index(tab: String) = checkAdmin(parser, exec).async { implicit request =>
    usersRepo.nasGroupAll.map { group =>
      Ok(views.html.admin.account(tab, group))
    }
  }

  def getList(string: String) = checkAdmin(parse.json, exec).async { implicit request =>
    val placeResult = request.body.validate[ListParameters]
    logger.debug(placeResult.toString)
    placeResult.fold(
      errors => {
        Future(BadRequest(Json.obj("code" -> 0, "message" -> JsError.toJson(errors), "count" -> 0, "data" -> Json.arr())))
      },
      p => {
        string match {
          case "user" => userList(p)
          case "group" => groupList(p)
          case "permission" => permissionList(p)
          case _ => Future(BadRequest(Json.obj("code" -> 0, "message" -> "JsError.toJson(errors)", "count" -> 0, "data" -> Json.arr())))
        }
      })

  }

  def userList(p: ListParameters) = {

    //    implicit val tableResJson = Json.format[UserInfo]
    usersRepo.usersListAll(name = p.query, page = p.page - 1, limit = p.limit, active = true).map {
      page => {
        val data = page._1.map { i =>
          Json.obj(
            "id" -> i.id,
            "company" -> services.dingtalk.DingtalkService.getCompanyName(i.company),
            "name" -> i.username,
            "position" -> i.position,
            "email" -> i.email,
            "mobile" -> i.mobile,
            "department" -> i.department,
            "active" -> (if (i.is_active > 0) "禁" else "是"),
            "accid" -> i.accountId
          )
        }
        Ok(Json.obj("code" -> 0, "message" -> "", "count" -> page._2, "data" -> Json.toJson(data)))
      }
    }
  }

  def groupList(p: ListParameters) = {
    //        implicit val tableResJson = Json.format[Group]
    usersRepo.nasGroupAll.flatMap { nasGroup =>
      usersRepo.groupListAll(name = p.query, page = p.page - 1, limit = p.limit, company = p.active.getOrElse("0").toInt).map {
        page => {
          val data = page._1.map { i =>
            val nas = if (nasGroup.filter(_.id.getOrElse(0) == i.nas_gid).isEmpty) NasGroup() else nasGroup.filter(_.id.get == i.nas_gid).head
            Json.obj(
              "id" -> i.id,
              "company" -> services.dingtalk.DingtalkService.getCompanyName(i.company),
              "name" -> i.pname,
              "parentid" -> i.parentid,
              "nas_gid" -> i.nas_gid,
              "nas_group" -> nas.pname,
              "nas_gname" -> nas.nas_name,
            )
          }
          Ok(Json.obj("code" -> 0, "message" -> "", "count" -> page._2, "data" -> Json.toJson(data)))
        }
      }
    }
  }

  def permissionList(p: ListParameters) = {
    //    implicit val tableResJson = Json.format[UserInfo]
    usersRepo.accountsListAll(name = p.query, page = p.page - 1, limit = p.limit, id = None).map {
      page => {
        val data = page._1.map { i =>
          Json.obj(
            "id" -> i.id,
            "name" -> i.username,
            "position" -> i.position,
            "mobile" -> i.mobile,
            "active" -> (if (i.permission == 0) "禁" else "是"),
            "permissions" -> PermissionAccess.getPermission(i.permission),
          )
        }
        Ok(Json.obj("code" -> 0, "message" -> "", "count" -> page._2, "data" -> Json.toJson(data)))
      }
    }
  }

  def updatePermission() = checkAdmin(parser, exec).async { implicit request =>
    val id: Seq[Int] = Seq()
    usersRepo.accountSetPermission().map(r => Ok(r.toString))
  }
}
